<template>
  <van-row class="mobile-bet">

    <van-row class="list" v-if="memberBets">

      <van-swipe-cell :right-width="65" v-for="(item,index) in memberBets" :key="index" :on-close="onCloseCell" :class="batchEdit == false || 'transform'">
        <van-cell-group>
          <van-cell :value="item.odd">
            <template>
              <van-row class="item">
                <van-col span="6">
                  <van-field @change="onCellInputChange(index)" v-model="bets[index].amount" placeholder="输入金额" />
                </van-col>
                <van-col span="14" style="padding-left:5px;">
                  <van-row style="text-align:left;color:gray;"> {{item.game_name}} </van-row>
                  <van-row style="font-size:12px;">
                    <van-col span="10"> {{item.lottery_name}} </van-col>
                    <van-col span="9"> {{item.page_name}} </van-col>
                    <van-col span="5" style="text-align:center"> {{item.content}} </van-col>
                  </van-row>
                </van-col>
                <van-col span="4" class="odd">{{item.odd}}</van-col>
              </van-row>
            </template>
          </van-cell>
        </van-cell-group>
        <div slot="right" @click="deleteItem(index)" class="delete">删除</div>
      </van-swipe-cell>

    </van-row>

    <van-row class="bottom" v-if="memberBets">

      <van-row class="amount">
        <van-col span="9">
          <van-field @change="onBatchAmountChange" v-model="batchAmount" placeholder="最低投注1.00元" />
        </van-col>
        <van-col span="5">
          <van-button @click="reset" size="small" class="btn" style="width:80%;margin-top:5px;">重置</van-button>
        </van-col>
        <van-col span="10">
          <van-button @click="preset" size="small" class="btn" style="width:80%;margin-top:5px;">预设金额</van-button>
        </van-col>
      </van-row>
      <van-row>
        <van-button @click="bet" type="primary" size="small" class="btn">投注</van-button>
      </van-row>
      <van-row class="result">
        <van-col span="12">总计组数:
          <span style="color:red;"> {{params.length}} </span>
        </van-col>
        <van-col span="12">总计投注:
          <span style="color:blue;"> ¥{{betsSum}} </span>
        </van-col>
      </van-row>

    </van-row>

    <van-popup v-model="showPopup" class="popup">
      <van-row class="title">
        请确认投注信息
      </van-row>
      <van-row>
        <van-col span="3"> 序号 </van-col>
        <van-col span="12"> 项目 </van-col>
        <van-col span="5"> 金额 </van-col>
        <van-col span="4"> 赔率 </van-col>
      </van-row>
      <van-row v-for="(item,index) in params" :key="`popupResult${index}`">
        <van-col span="3"> {{index+1}} </van-col>
        <van-col span="12">
          <div>
            {{memberBets[item.option].game_name}}
          </div>
          <div>
            {{memberBets[item.option].lottery_name}} {{memberBets[item.option].page_name}} {{memberBets[item.option].content}}
          </div>
        </van-col>
        <van-col span="5"> {{item.amount}} </van-col>
        <van-col span="4"> {{memberBets[item.option].odd}} </van-col>
      </van-row>
      <van-row>
        <van-col span="12">总计组数:
          <span style="color:red">{{params.length}}</span>
        </van-col>
        <van-col span="12">总计投注:
          <span style="color:blue">¥{{betsSum}}</span>
        </van-col>
      </van-row>
      <van-row class="btn">
        <van-button @click="showPopup = false" type="default" size="small">取消</van-button>
        <van-button @click="submit" type="primary" size="small" :loading="loading">确认</van-button>
      </van-row>
    </van-popup>

  </van-row>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { formatFloat } from '@/utils/index'

  import {
    Row,
    Col,
    Button,
    Cell,
    CellGroup,
    SwipeCell,
    Icon,
    Field,
    Toast,
    Popup,
    Dialog,
  } from 'vant'

  export default {
    components: {
      [Row.name]: Row,
      [Col.name]: Col,
      [Button.name]: Button,
      [Cell.name]: Cell,
      [CellGroup.name]: CellGroup,
      [SwipeCell.name]: SwipeCell,
      [Icon.name]: Icon,
      [Field.name]: Field,
      [Toast.name]: Toast,
      [Popup.name]: Popup,
      [Dialog.name]: Dialog,
    },

    data() {
      return {
        loading: false,
        showPopup: false,
        batchAmount: null, // 批量金额
        bets: {},
        params: [], // 提交的参数
        batchEdit: false,
      }
    },

    computed: {
      ...mapGetters(['memberGameSelected', 'memberBets', 'memberInfo']),
      betsSum() {
        let sum = 0
        let passedItems = []
        for (const key in this.bets) {
          if (this.bets.hasOwnProperty(key)) {
            const element = this.bets[key]
            let amountNumber = Number(element.amount)
            if (amountNumber != NaN && amountNumber > 0) {
              sum += amountNumber
              // 保存合法item,用于提交
              passedItems.push({
                option: element.option,
                content: element.content,
                amount: amountNumber,
              })
            }
          }
        }
        this.params = passedItems
        console.log(this.params)

        // 同时更新store
        this.$store.commit(
          'MEMBER_SET_BETS',
          JSON.parse(JSON.stringify(this.bets)),
        )
        return (Math.round(Number(sum) * 100) / 100).toFixed(2)
      },
    },

    // 数据格式化
    filters: {},

    created() {
      this.bets = JSON.parse(JSON.stringify(this.memberBets))
    },

    methods: {
      deleteItem(option_code) {
        let temp = JSON.parse(JSON.stringify(this.bets))
        delete temp[option_code] // 同时删除
        //目的是实现显性操作,不然页面不会重新渲染
        this.bets = temp
        //保存到store 深复制
        this.$store.commit('MEMBER_SET_BETS', this.bets)
      },

      onCellInputChange(option_code) {
        let amount = Number(this.bets[option_code].amount)
        if (amount != NaN && amount >= 0) {
          this.bets[option_code].amount = (
            Math.round(Number(amount) * 100) / 100
          ).toFixed(2)
        } else {
          Toast('请填写有效数字金额')
        }
      },

      onBatchAmountChange() {
        let amount = Number(this.batchAmount)
        if (amount != NaN && amount >= 0) {
          this.batchAmount = (Math.round(amount * 100) / 100).toFixed(2)
        } else {
          Toast('请填写有效数字金额')
        }
      },

      reset() {
        this.batchAmount = ''
      },

      preset() {
        console.log('peset')
        this.batchEdit = !this.batchEdit
      },

      onCloseCell(...args) {
        console.log(args)
      },

      bet() {
        console.log(this.params)
        if (this.params.length <= 0) {
          Toast('未有投注项目')
        } else {
          this.showPopup = true
        }
      },

      submit() {
        const params = {
          period: 677916,
          game: this.memberGameSelected,
          bets: this.params,
        }
        this.$store
          .dispatch('MemberBet', params)
          .then(response => {
            this.loading = false
            console.log(response)

            if (response && response[0] && response[0].order_no) {
              // 登录成功
              Toast.success('提交成功!')
              this.showPopup = false
              // 清空inputs
              this.reset()
            } else {
              // 失败
              this.showPopup = false
              this.$dialog.alert({
                title: '投注失败',
                message: Object.values(response)[0].toString(),
              })
            }
          })
          .catch(() => {
            this.loading = false
          })
      },
    },
    watch: {
      batchAmount(to, from) {
        if (Number(to) != NaN && Number(to) >= 0) {
          for (const key in this.bets) {
            if (this.bets.hasOwnProperty(key)) {
              const element = this.bets[key]
              element.amount = Number(to)
            }
          }
        }
      },
    },
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  @import 'src/styles/variables.scss';

  .mobile-bet {
    text-align: center;
    .list {
      padding-bottom: 136px;
      .item {
        .van-col:first-of-type {
          .van-field {
            margin-top: 5px;
            border: 1px solid $bgc;
            padding: 10px;
          }
        }
        .odd {
          text-align: right;
          height: 48px;
          line-height: 48px;
          color: red;
        }
      }
      .delete {
        color: #fff;
        background-color: red;
        width: 65px;
        height: 100%;
        line-height: 68px;
        font-weight: 700;
      }
      // 向左滑动
      .transform {
        transform: translate3d(-65px, 0px, 0px);
        transition: 0.6s cubic-bezier(0.18, 0.89, 0.32, 1);
      }
    }

    .bottom {
      width: 100%;
      position: fixed;
      bottom: 50px;
      background-color: #fff;
      padding: 10px 0;
      .van-row {
        padding: 5px 0;
      }
      .amount {
        padding-left: 5%;
        .van-field {
          border: 1px solid $bgc;
        }
      }
      .btn {
        width: 90%;
        font-weight: 700;
        font-size: 16px;
      }
      .result {
        .van-col:last-of-type {
          text-align: right;
          padding-right: 5%;
        }
        .van-col:first-of-type {
          text-align: left;
          padding-left: 5%;
        }
      }
    }

    .popup {
      width: 90%;
      font-size: 13px;
      .van-row {
        padding: 5px 0;
      }
      .title {
        font-size: 14px;
        border-bottom: 1px solid $bgc;
        padding: 8px 0;
      }
      .btn {
        .van-button {
          margin: 0 10px;
          width: 25%;
        }
      }
    }
  }
</style>